package com.rtwo.tio.client;

import com.rtwo.tio.client.handler.GroupMsgRequestHandler;
import com.rtwo.tio.client.handler.JoinGroupRequestHandler;
import com.rtwo.tio.client.handler.LoginRequestHandler;
import com.rtwo.tio.client.handler.P2PRequestHandler;
import com.rtwo.tio.common.BasicHandler;
import com.rtwo.tio.common.BasicPacket;
import com.rtwo.tio.common.MsgType;
import com.rtwo.tio.common.TioHandler;
import com.rtwo.tio.common.heartbeat.HeartBeatMsg;
import org.tio.client.intf.ClientAioHandler;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.utils.json.Json;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by hasee on 2018/7/4.
 */
public class ClientTioHandlerImp extends TioHandler implements ClientAioHandler {

    private static Map<Byte,BasicHandler<?>> handlers = new HashMap<>();

    static
    {
        handlers.put(MsgType.LOGIN_RESP,new LoginRequestHandler());
        handlers.put(MsgType.P2P_RESP,new P2PRequestHandler());
        handlers.put(MsgType.GROUP_JOIN_RESP,new JoinGroupRequestHandler());
        handlers.put(MsgType.GROUP_MSG_RESP,new GroupMsgRequestHandler());
    }

    @Override
    public Packet heartbeatPacket() {
        HeartBeatMsg heartBeatMsg = new HeartBeatMsg();
        return new BasicPacket(MsgType.HEART_BEAT_REQ,Json.toJson(heartBeatMsg).getBytes());
    }

    @Override
    public void handler(Packet packet, ChannelContext channelContext) throws Exception {
        BasicPacket basicPacket = (BasicPacket)packet;
        byte type = basicPacket.getType();
        BasicHandler<?> _handler = handlers.get(type);
        _handler.handler(packet,channelContext);
    }
}
